<template>
	<!-- 2023年4月5日 李琛 首页客服组件 -->
	<div id="customer_box">
		<div id="div1" @click="saveFriend()">
		</div>
		<div v-drag v-if="customerWindow" id="customerWindow">
			<div class="customer_window_header">
				{{inceptForm.userName}}
				<i @click="close" class="el-icon-close"></i>
			</div>
			<div class="customer_window_main">
				<div class="wxchatBorderRightMid">
					<div style="margin-top: 15px;">
					<el-row>
						<el-col>
							<div id="chatPop1" style=" overflow-y:auto; height:350px;width:100%;flex-direction: column-reverse;">
								<div>
									<!-- 聊天记录item -->
									<div class="chat-item" v-for="(item) in msg" :key="item.id" :id="'msg' + item.id">
										<!-- 时间  -->
										<!-- <div class="time" v-if="item.is_withdrawn === 0">{{item.send_time}}</div> -->
										<!-- <div class="time">{{warning}}</div> -->
										<!--a - 自己的信息-->
										<div class="content-wrapper-right" v-if="item.serderId == userId">
											<!-- 头像 -->
											<img  class="avator-avator-right" :src="userForm.avatarUrl" style="width:40px;height:40px;margin-top:5px"/>
											<div style="width: 284px;float: right;">
												<!-- text - 文字 -->
												<div class="chat-content-right">{{item.content}}</div>
											</div>
										</div>
										<!-- b - 对方的消息  -->
										<div class="content-wrapper-left" v-if="item.serderId !== userId">
											<!-- 头像 -->
											<img  class="avator-avator-left" :src="$imageUrl + '?id=' + inceptForm.avatarId" style="width:40px;height:40px;margin-top:5px"/>
											<div style="width: 284px;float: left;">
												<!-- text - 文字 -->
												<div class="chat-content-left">{{item.content}}</div>
											</div>
										</div>
									</div>
								</div>
							</div>
						</el-col>
					</el-row>
					</div>
				</div>
				<el-input
					type="textarea"
					:rows="2"
					placeholder="请输入内容"
					@keyup.enter.native="sendMsg"
					v-model="content">
				</el-input>
				<el-button @click="sendMsg">发送</el-button>
			</div>
		</div>
	</div>
</template>
<script>
export default {
	name: "CustomerHome",
  	// 自定义指令 实现可拖动
	directives: {
		drag: {
            // 指令的定义
            bind: function(el) {
                let oDiv = el;  // 获取当前元素
                oDiv.onmousedown = (e) => {
                    // 算出鼠标相对元素的位置
                    let disX = e.clientX - oDiv.offsetLeft;
                    let disY = e.clientY - oDiv.offsetTop;

                    document.onmousemove = (e) => {
                        // 用鼠标的位置减去鼠标相对元素的位置，得到元素的位置
                        let left = e.clientX - disX;
                        let top = e.clientY - disY;

                        oDiv.style.left = left + 'px';
                        oDiv.style.top = top + 'px';
                        
                    };

                    document.onmouseup = (e) => {
                        document.onmousemove = null;
                        document.onmouseup = null;
                    }
                }
            }
        }
	},
	data() {
		return {
			// 用户id
			userId: 0,
			//客服窗口
			customerWindow: false,
			// 客服按钮
			customerBtn: true,
			ws: null,
			// 消息接收人
			inceptId: 0,
			// 消息
			content: '',
			// 消息记录
			msg: [],
			// 当前登录的用户信息
			userForm: null,
			// 接收人对象
			inceptForm: {},
			// 聊天内容
			lt: {
				"inceptId":"",
				"content":"",
				"senderId":"",
			},
			// 连接角色 0普通用户 1客服
			role: 0,
			// 警告
			warning: ''
		}
	},
	watch: {
		inceptId(oldData, newData){
			// 获取接收人信息
			this.getInceptById()
		},
		'msg': 'updateScroll'
	},
	created () {
		this.userId = window.sessionStorage.getItem("userId")
	},
	mounted () {
	},
	methods: {
		// 将滚动条在底部
		updateScroll(){
			this.$nextTick(() => {
				var element = document.getElementById("chatPop1");
				element.scrollTop = element.scrollHeight;
			})
		},
		// 获取发信息的用户信息
		getUserById(){
			this.$axios.get('/upUser/getUserById', {
					params:{
						id: this.userId
					}
				}).then(res => {
				if (res.data.flag) {
					this.userForm = res.data.data
				} else {

				}
			})
		},
		// 发送消息
		sendMsg () {
			if (this.content.trim() !== '') {
				// 消息接收人
				this.lt.inceptId = this.inceptId
				// 发送信息内容
				this.lt.content = this.content
				// 发送人
				this.lt.senderId = this.userId
				this.ws.send(JSON.stringify(this.lt))
				var obj = {}
				obj.avatarUrl = this.userForm.avatarUrl
				obj.content = this.content
				obj.serderId = this.userId
				this.msg.push(obj)
				this.content = ''
			} else {
				this.message("不能发送空消息", "warning")
				// 清除文本框空格
				this.content = this.content.trim()
			}
		},
		// 关闭客服窗口
		close(){
			this.customerBtn = true
			this.customerWindow = false
		},
		// 新增会话
		saveFriend () {
			// 获取当前登录用户信息
			if (this.userId != null & this.userId != 'null' & this.userForm == null) {
				// 根据用户id获取用户信息
				this.getUserById()
			}
			const that = this
			if (this.userId == null || this.userId == 'null' && this.ws == null) {
				this.$router.push({path: "/Login"})
			} else {
				// 显示客服窗口
				this.customerWindow = true
				// 判断是否已经连接过
				if (this.ws == null) {
					this.ws = new WebSocket(that.$ws + "/customerWebSocket/" + this.userId + "/" + this.role)
				}
				this.ws.onopen = function (event) {

				}

				//接收到消息的回调方法
				this.ws.onmessage = function (msg) {
					var data = JSON.parse(msg.data)
					console.log(data)
					if (data.customerOnlineFlag) {
						if (data.inceptId != 0) {
							// 赋值消息接收人id
							that.inceptId = data.inceptId
						}
						var obj = {}
						// 对方发的消息
						obj.content = data.context
						// 发送人的id
						obj.serderId = data.sender
						that.msg.push(obj)
					} else {
						that.message("客服还未上线", "warning")
						// 关闭聊天窗口
						that.customerWindow = false
						// that.warning = "客服还未上线"
					}
				}

				//连接关闭的回调方法
				this.ws.onclose = function () {
					// 关闭连接时保存用户聊天记录
					that.saveChatRecord()
				}
			}
		},
		// 保存用户聊天记录
		saveChatRecord () {
			this.$axios.post("/customer/saveChatRecord", {
				msg: JSON.stringify(this.msg),
				userId: JSON.stringify(this.userId)
			}).then(res => {
				
			})
		},
		// 获取消息接收人详细信息
		getInceptById(){
			this.$axios.get("/sysUser/getUserById", {
				params: {
					id: this.inceptId
				}
			}).then(res => {
				console.log(res)
				if (res.data.flag) {
					this.inceptForm = res.data.data
					console.log(this.inceptForm)
				} else {

				}
			})
		},
		// 消息提示框
		message (message, type) {
			this.$message({
				message: message,
				type: type
			})
		}
	}
}
</script>

<style scoped>
#customer_box{
	width: 100%;
	height: 100%;
	position: relative;
}
#div1{
	position: fixed;
	bottom: 16%;
	right:4%;
	width: 50px;
	height: 50px;
	background: #FFF200;
	border-radius: 50%;
	background-image: url('../../assets/image/customer.png');
	background-position: center;
	background-repeat: no-repeat;
	background-size: 60%;
	cursor:pointer;
}
#div1:hover{
	background-image: url('../../assets/image/customer1.png');
	background-position: center;
	background-repeat: no-repeat;
	background-size: 60%;
	cursor:pointer;
}
#customerWindow{
	position: fixed;
	bottom: 16%;
	right:4%;
	width: 400px;
	height: 500px;
	background-color: white;
	box-shadow:4px 4px 15px rgb(144, 144, 144);
}
.customer_window_header{
	width: 100%;
	height: 60px;
	background-color: #FFF200;
}
.el-icon-close{
	cursor: pointer;
	position: absolute;
	right: 10px;
	top: 10px;
}
.wxchatBorderRightMid {
	width: 100%;
	height: 100%;
	background-color: #f5f5f5;
	display: block;
	float: left;
}
/* 聊天样式 */
#chatPop1 span {
	background-color: #fff;
	padding: 5px 8px;
	display: inline-block;
	border-radius: 10px;
	margin: 0px 0 10px 10px;
	position: relative;
	border: 1px solid #E3E3E3;
	max-width: 290px;
}

#chatPop1 span::after {
	content: '';
	border: 8px solid #ffffff00;
	border-right: 8px solid #fff;
	position: absolute;
	top: 8px;
	left: -16px;
}
/* 消息样式 */
.chat-item{
	font-size: 15px;
	color: #000000;
}
.time{
	width: 100%;
	height: 18px;
	color: #000000;
	margin-left: auto;
	margin-right: auto;
	text-align: center;
	font-size: 13px;
	margin-top: 10px;
	z-index: 2;
}
.content-wrapper-right{
	display: flow-root;
	padding: 10px 10px 0 10px;
}
.avator-avator-right{
	width: 50px;
	height: 50px;
	border-radius: 50%;
	border: #fff solid 1px;
	float: right;
}
.chat-content-right{
	float: right;
	background-color: #95ec69;
	margin-right: 6px;
	padding: 4px 10px;
	border-radius: 6px;
	margin-top: 8px;
	line-height: 28px;
}
.content-wrapper-left{
	display: flow-root;
	padding: 10px 10px 0 10px;
}
.avator-avator-left{
	width: 50px;
	height: 50px;
	border-radius: 50%;
	border: #fff solid 1px;
	float: left;
}
.chat-content-left{
	float: left;
	background-color: #fff;
	margin-left: 6px;
	padding: 4px 10px;
	border-radius: 6px;
	margin-top: 8px;
	line-height: 28px;
	word-break:break-all;
}
</style>